package com.tucc.hello.leetcode.no1_400.no1_200.no81_100.no92;

import com.tucc.hello.leetcode.common.ListNode;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode head = ListNode.of(1, 2, 3, 4, 5);
        ListNode newHead = solution.reverseBetween(head, 1, 1);
        ListNode.print(newHead);
    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (head == null) {
            return null;
        }
        ListNode newHead = null;
        int count = 0;
        ListNode next = head;
        ListNode pre = null;
        ListNode firstPre = null;
        ListNode temp = null;
        ListNode tail = null;
        while (next != null) {
            count++;
            if (count < left && newHead == null) {
                newHead = next;
                tail = next;
                next = next.next;
                tail.next = null;
            } else if (count >= left && count <= right) {
                temp = next.next;
                next.next = pre;
                pre = next;
                next = temp;
                if (firstPre == null) {
                    firstPre = pre;
                }
                if (count == right) {
                    if (newHead == null) {
                        newHead = pre;
                        tail = firstPre;
                    } else {
                        tail.next = pre;
                        tail = firstPre;
                    }
                }
            } else {
                tail.next = next;
                next = next.next;
                tail = tail.next;
                tail.next = null;
            }
        }

        return newHead;
    }
}
